package com.illtamer.infinite.derive;

import com.illtamer.infinite.derive.path.FilePath;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public final class Resource {

    private Resource() {}


    public Path root(String filePath) {
        return new FilePath(filePath);
    }

    public Path root(File file) {
        return new FilePath(file);
    }

    public static Resource instance() {
        return ResourceHolder.RESOURCE;
    }

    @Nullable
    public static Path getPath(Path root, String relativePath) {
        if (relativePath == null || relativePath.length() == 0) return root;
        final String[] splits = relativePath.substring(1).split("/");
        int index = 0;
        while (index < splits.length) {
            if (!root.getName().equals(splits[index])) return null;
            if (index+1 == splits.length) return root;
            int targetIndex = index + 1;
            Path next = root.list().stream().filter(path -> path.getName().equals(splits[targetIndex])).findFirst().orElse(null);
            if (next == null) return null;
            root = next;
            ++ index;
        }
        return null;
    }

    private static class ResourceHolder {
        private static final Resource RESOURCE = new Resource();
    }

}
